<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动观察元素是否可见</title>
    <style>
       * {
            padding:0;
            margin:0;
            font-size: 12px;
        }
        .box-item {
            width: 300px;
            min-height:200px;
            overflow: hidden;
            border:1px solid #999;
            margin-bottom: 30px;
        }
        .box-item img {
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="box-container" id="example">
        <div class="box-item">
            <img data-src="http://azure.summerfarm.net/test/jrpsnkdk6t87lole.png" class="lazy-loaded" src="http://azure.summerfarm.net/goods-default.jpg" alt="">
        </div>
        <div class="box-item">
            <img data-src="http://azure.summerfarm.net/test/ek6njhsae6g7wtq3.png" class="lazy-loaded" src="http://azure.summerfarm.net/goods-default.jpg" alt="">
        </div>
        <div class="box-item">
            <img data-src="http://azure.summerfarm.net/test/hxccu97fbx95kb3k.jpg" class="lazy-loaded" src="http://azure.summerfarm.net/goods-default.jpg" alt="">
        </div>
        <div class="box-item">
            <img data-src="http://azure.summerfarm.net/test/dk4ma32b8qlzdh4k.JPG" class="lazy-loaded" src="http://azure.summerfarm.net/goods-default.jpg" alt="">
        </div>
        <div class="box-item">
            <img data-src="http://azure.summerfarm.net/test/ek6njhsae6g7wtq3.png" class="lazy-loaded" src="http://azure.summerfarm.net/goods-default.jpg" alt="">
        </div>
    </div>
</body>
<script>
// 由于可见（visible）的本质是，目标元素与视口产生一个交叉区，所以这个 API 叫做"交叉观察器"。
// var io = new IntersectionObserver((entries) => {
//     console.log(999999, entries)
// }, {
//     threshold: [0, 0.25, 0.5, 0.75, 1]
// });
// io.observe(document.getElementById('example1'));


function query(selector) {
  return Array.from(document.querySelectorAll(selector));
}

var observer = new IntersectionObserver(
  function(changes) {
    changes.forEach(function(change) {
        if (change.isIntersecting) {
            const img = change.target
            const src = img.getAttribute('data-src')
            console.log('src==', src)
            // 加载图片
            img.setAttribute('src', src);

            observer.unobserve(img);
        }
    });
  }
);

query('.lazy-loaded').forEach(function (item) {
  observer.observe(item);
});
</script>
</html>